package cn.zjitc.exam.controller;

import cn.zjitc.exam.domain.Product;
import cn.zjitc.exam.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * author: 李林凯
 * time:2025/6/18 19:26
 **/
@Controller
@RequestMapping("/product")
public class ProductController {
    @Autowired
    private ProductService productService;
    @GetMapping("/add")
    public String addPage(){
        return "product/add";
    }
    @PostMapping("/add")
    public String addProduct(Product product){
        productService.insert(product);
        return "redirect:/product/list";
    }
    @PostMapping("/delete/{id}")
    public String deleteProduct(@PathVariable("id") int id){
        productService.delete(id);
        return "redirect:/product/list";
    }
    @GetMapping("/edit/{id}")
    public String editPage(@PathVariable("id") int id, Model model){
        productService.findById(id);
        model.addAttribute("product", productService.findById(id));
        return "product/edit";
    }
    @PostMapping("/edit")
    public String editProduct(Product product){
        productService.update(product);
        return "redirect:/product/list";
    }
    @GetMapping("/list")
    public String listPage(@RequestParam(defaultValue = "1") int page,
                           @RequestParam(defaultValue = "5") int pageSize,Model model){
        List<Product> products=productService.getProductByPage(page, pageSize);
        int total=productService.getProductCount();
        model.addAttribute("products", products);
        model.addAttribute("total", total);
        model.addAttribute("page", page);
        model.addAttribute("size", pageSize);
        return "product/list";
    }
    @GetMapping("/search")
    public String search(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "5") int pageSize,
            @RequestParam String keyword,
            Model model
    ) {
        // 调用带分页的搜索方法
        List<Product> products = productService.searchByKeyword(keyword, page, pageSize);
        int total = productService.countByKeyword(keyword);

        // 传递数据到视图
        model.addAttribute("products", products);
        model.addAttribute("total", total);
        model.addAttribute("page", page);
        model.addAttribute("size", pageSize);
        model.addAttribute("keyword", keyword); // 回显搜索关键词

        return "product/list";
    }
    @ExceptionHandler(NumberFormatException.class)
    public ModelAndView handleNumberFormatException(NumberFormatException ex) {
        ModelAndView modelView = new ModelAndView("error");
        modelView.addObject("errorMsg", "输入的数值格式不正确或超出范围");
        return modelView;
    }

}
